<?php
class Util
{
    public static function getContentsCurl($url)
    {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_HEADER			, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER	, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION	, 1);
        curl_setopt($ch, CURLOPT_URL			, $url);

        $data = curl_exec($ch);
        curl_close($ch);

        return $data;
    }

    public static function saveJson($array, $file)
    {
        $fp = fopen($file . ".json", "w");
        fwrite($fp, json_encode($array));
        fclose($fp);
    }

    public static function readFromPSD($id)
    {
        $html = Util::getContentsCurl(HGA_PATH_FROM_PSD . $id);
        $dom = new DOMDocument();
        //$dom = new DOMDocument('4.01', 'iso-8859-1');
        @$dom->loadHTML($html);

        $table  = $dom->getElementsByTagname('table');
        $tr     = $table->item(2)->getElementsByTagname('tr');

        $arr = array();
        for ($i=3; $i<$tr->length; $i++)
        {
            $td = $tr->item($i)->getElementsByTagname('td');
            foreach ($td->item(0)->getElementsByTagname('a') as $link);
            {
                $href = $link->getAttribute('href');
            }
            $line    = $td->item(0)->nodeValue . "\n";
            $explode = explode('-', $line);

            $info = array(
                HGA_PLAYER_NUMBER   => trim($explode[0]),
                HGA_PLAYER_NAME     => trim($explode[1]),
                HGA_PLAYER_UPDATE   => Util::getLastUpdateFromPSD($href),
            );

            $arr[] = $info;
        }
        return $arr;
    }

    public static function getLastUpdateFromPSD($url)
    {
        $html = Util::getContentsCurl(HGA_PATH_HOME_PSD . $url);
        $dom = new DOMDocument();
        @$dom->loadHTML($html);

        $table  = $dom->getElementsByTagName('table');
        $tr     = $table->item(1)->getElementsByTagName('tr');
        $td     = $tr->item(5)->getElementsByTagName('td');
        $i      = $td->item(0)->getElementsByTagName('i');
        $b      = $i->item(0)->getElementsByTagName('b');
        $arr    = explode(' ', $b->item(0)->nodeValue);
        return $arr[0];
    }
}

